<script setup>
import { addGoodsAPI, deleteGoodsAPI, destroyGoodsAPI, getGoodsListAPI, restoreGoodsAPI, updateGoodsAPI, updateGoodsStatusAPI } from '@/api/goods'
import ChooseImage from '@/components/ChooseImage.vue'
import Search from '@/components/Search.vue'
import SearchItem from '@/components/SearchItem.vue'
import FormDrawer from '@/components/FormDrawer.vue'
import { ref } from 'vue'
import { useInitForm, useInitTable } from '@/composables/useCommon'
import ListHeader from '@/components/ListHeader.vue'
import { getCategoryListAPI } from '@/api/category'
import banners from './banners.vue'
import Content from './content.vue'
import Skus from './skus.vue'
import { toast } from '@/composables/util'
const {
  handleSelectionChange,
  multipleTableRef,
  handleMultiDelete,
  searchForm,
  resetSearchForm,
  tableData,
  loading,
  total,
  currentPage,
  handleMultiStatusChange,
  handleDelete,
  getData,
  multiSelectionIds
} = useInitTable(
  {
    searchForm: {
      title: '',
      tab: 'all',
      category_id: null
    },
    getList: getGoodsListAPI,
    onGetListSuccess: (res) => {
      tableData.value = res.list.map((o) => {
        o.bannersLoading = false
        o.contentLoading = false
        o.skusLoading = false
        return o
      })
      total.value = res.totalCount
    },
    delete: deleteGoodsAPI,
    updateStatus: updateGoodsStatusAPI
  }
)

const {
  form,
  formDrawerRef,
  formRef,
  drawerTitle,
  handleEdit,
  handleSubmit,
  handleCreate,

} = useInitForm(
  {
    form: {
      title: null, //商品名称
      category_id: null, //商品分类
      cover: null, //商品封面
      desc: null, //商品描述
      unit: "件", //商品单位
      stock: 100, //总库存
      min_stock: 10, //库存预警
      status: 1, //是否上架 0仓库1上架
      stock_display: 1, //库存显示 0隐藏1显示
      min_price: 0, //最低销售价
      min_oprice: 0 //最低原价
    },
    getData,
    update: updateGoodsAPI,
    add: addGoodsAPI
  }
)

const handleCurrentChange = (val) => {
  currentPage.value = val
  getData()
}

const tabbars = [
  {
    key: 'all',
    name: '全部'
  },
  {
    key: 'checking',
    name: '审核中'
  },
  {
    key: 'saling',
    name: '出售中'
  },
  {
    key: 'off',
    name: '已下架'
  },
  {
    key: 'min_stock',
    name: '库存预警'
  },
  {
    key: 'delete',
    name: '回收站'
  }
]

// 商品分类
const category_list = ref([])
getCategoryListAPI().then(res => {
  category_list.value = res
})

// 设置轮播图
const bannersRef = ref(null)
const handleSetGoodsBanners = (row) => {
  bannersRef.value.open(row)
}
// 设置商品详情
const contentRef = ref(null)
const handleSetGoodsContent = (row) => {
  contentRef.value.open(row)
}
// 设置商品规格
const skusRef = ref(null)
const handleSetGoodsSkus = (row) => {
  skusRef.value.open(row)
}
const handleRestoreGoods = () => {
  loading.value = true
  restoreGoodsAPI(multiSelectionIds.value).then(res => {
    toast('恢复商品成功')
    if (multipleTableRef.value) {
      multipleTableRef.value.clearSelection()
    }
    getData()
  })
    .finally(() => {
      loading.value = false
    })
}
const handleDestroyGoods = () => {
  loading.value = true
  destroyGoodsAPI(multiSelectionIds.value).then(res => {
    toast('删除商品成功')
    if (multipleTableRef.value) {
      multipleTableRef.value.clearSelection()
    }
    getData()
  })
    .finally(() => {
      loading.value = false
    })
}
</script>

<template>
  <div>
    <el-tabs v-model="searchForm.tab" @tab-change="getData">
      <el-tab-pane v-for="(item, index) in tabbars" :key="index" :label="item.name" :name="item.key"></el-tab-pane>
    </el-tabs>
    <el-card>
      <!-- 搜索 -->
      <Search @search="getData" @reset="resetSearchForm" :model="searchForm">
        <SearchItem label="关键词">
          <el-input v-model="searchForm.title" placeholder="商品名称" clearable></el-input>
        </SearchItem>
        <template #show>
          <SearchItem label="商品分类">
            <el-select v-model="searchForm.category_id" placeholder="请选择商品分类" clearable>
              <el-option v-for="item in category_list" :key="item.id" :label="item.name" :value="item.id">
              </el-option>
            </el-select>
          </SearchItem>
        </template>
      </Search>
      <!-- 新增 刷新 -->
      <ListHeader layout="create,refresh" @create="handleCreate" @refresh="getData">
        <el-button type="danger" size="small" @click="handleMultiDelete"
          v-if="searchForm.tab !== 'delete'">批量删除</el-button>
        <el-button type="warning" size="small" @click="handleRestoreGoods" v-else>恢复商品</el-button>
        <el-popconfirm v-if="searchForm.tab === 'delete'" @confirm="handleDestroyGoods" confirm-button-text="确认"
          cancel-button-text="取消" title="你确定要删除吗?">
          <template #reference>
            <el-button type="danger" size="small">彻底删除</el-button>
          </template>
        </el-popconfirm>
        <el-button size="small" @click="handleMultiStatusChange(1)"
          v-if="searchForm.tab === 'all' || searchForm.tab === 'off'">上架</el-button>
        <el-button size="small" @click="handleMultiStatusChange(0)"
          v-if="searchForm.tab === 'all' || searchForm.tab === 'saling'">下架</el-button>
      </ListHeader>
      <!-- 表格区域 -->
      <el-table ref="multipleTableRef" @selection-change="handleSelectionChange" class="mt-3" v-loading="loading"
        :data="tableData" border stripe style="width: 100%;">
        <el-table-column type="selection" width="55"></el-table-column>

        <el-table-column label="商品" width="300">
          <template #default="scope">
            <div class="flex ">
              <el-image class="mr-3 rounded" :src="scope.row.cover" fit="cover" :lazy="true"
                style="width: 50px; height: 50px;"></el-image>
              <div class="flex-1">
                <p>{{ scope.row.title }}</p>
                <div>
                  <span class="text-rose-500">￥{{ scope.row.min_price }}</span>
                  <el-divider direction="vertical"></el-divider>
                  <span class="text-gray-500 text-xs">￥{{ scope.row.min_oprice }}</span>
                </div>
                <p class="text-gray-400 text-xs mb-1">分类:{{ scope.row.category ? scope.row.category.name : '未分类' }}
                </p>
                <p class="text-gray-400 text-xs">创建时间:{{ scope.row.create_time }}</p>
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="实际销量" prop="sale_count" width="90" align="center"></el-table-column>
        <el-table-column label="商品状态" align="center" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status ? 'success' : 'danger'" size="small">{{ row.status ? '上架' : '仓库' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="审核状态" align="center" width="120" v-if="searchForm.tab !== 'delete'">
          <template #default="{ row }">
            <div v-if="row.ischeck === 0" class="flex flex-col">
              <el-button type="success" size="small" plain>审核通过</el-button>
              <el-button class="mt-2 !ml-0" type="danger" size="small" plain>审核拒绝</el-button>
            </div>
            <span v-else>{{ row.ischeck === 1 ? '通过' : '拒绝' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="总库存" prop="stock" width="90" align="center"></el-table-column>


        <el-table-column label="操作" align="center">
          <template #default="scope">
            <div v-if="searchForm.tab !== 'delete'">
              <el-button class="px-1" type="primary" size="small" text @click="handleEdit(scope.row)">修改</el-button>
              <el-button class="px-1"
                :type="(scope.row.sku_type === 0 && !scope.row.sku_value) || (scope.row.sku_type === 1 && !scope.row.goods_skus.length) ? 'danger' : 'primary'"
                size="small" text @click="handleSetGoodsSkus(scope.row)"
                :loading="scope.row.skusLoading">商品规格</el-button>
              <el-button class="px-1" :type="scope.row.goods_banner.length === 0 ? 'danger' : 'primary'" size="small"
                text @click="handleSetGoodsBanners(scope.row)" :loading="scope.row.bannersLoading">设置轮播图</el-button>
              <el-button @click="handleSetGoodsContent(scope.row)" :loading="scope.row.contentLoading"
                :type="!scope.row.content ? 'danger' : 'primary'" class="px-1" type="primary" size="small"
                text>商品详情</el-button>
              <el-popconfirm @confirm="handleDelete([scope.row.id])" confirm-button-text="确认" cancel-button-text="取消"
                title="你确定要删除吗?">
                <template #reference>
                  <el-button class="px-1" type="primary" size="small" text>删除</el-button>
                </template>
              </el-popconfirm>
            </div>
            <span v-else>暂无操作</span>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination class="flex justify-center mt-auto-3" background layout="prev, pager, next" :total="total"
        :current-page="currentPage" @current-change="handleCurrentChange" />

      <FormDrawer ref="formDrawerRef" :title="drawerTitle + '管理员'" @submit="handleSubmit">
        <el-form :model="form" label-width="80">
          <el-form-item label="商品名称" prop="title">
            <el-input placeholder="请输入商品名称,不能超过60个字符" v-model="form.title"></el-input>
          </el-form-item>
          <el-form-item label="封面" prop="cover">
            <ChooseImage v-model="form.cover"></ChooseImage>
          </el-form-item>
          <el-form-item label="商品分类" prop="category_id">
            <el-select v-model="form.category_id" placeholder="选择商品分类">
              <el-option v-for="item in category_list" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="商品描述" prop="desc">
            <el-input type="textarea" placeholder="请输入商品描述" v-model="form.desc"></el-input>
          </el-form-item>
          <el-form-item label="单位" prop="unit">
            <el-input placeholder="请输入单位" style="width: 50%;" v-model="form.unit"></el-input>
          </el-form-item>
          <el-form-item label="总库存" prop="stock">
            <el-input v-model="form.stock" type="number" style="width: 40%;">
              <template #append>件</template>
            </el-input>
          </el-form-item>
          <el-form-item label="库存预警" prop="min_stock">
            <el-input v-model="form.min_stock" type="number" style="width: 40%;">
              <template #append>件</template>
            </el-input>
          </el-form-item>
          <el-form-item label="最低销售价" prop="min_price">
            <el-input v-model="form.min_price" type="number" style="width: 40%;">
              <template #append>元</template>
            </el-input>
          </el-form-item>
          <el-form-item label="最低原价" prop="min_oprice">
            <el-input v-model="form.min_oprice" type="number" style="width: 40%;">
              <template #append>元</template>
            </el-input>
          </el-form-item>
          <el-form-item label="库存显示" prop="stock_display">
            <el-radio-group v-model="form.stock_display">
              <el-radio :value="0">隐藏</el-radio>
              <el-radio :value="1">显示</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="是否上架" prop="status">
            <el-radio-group v-model="form.status">
              <el-radio :value="0">放入仓库</el-radio>
              <el-radio :value="1">立即上架</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
      </FormDrawer>
    </el-card>
    <banners ref="bannersRef" @reload-data="getData"></banners>
    <Content ref="contentRef" @reload-data="getData"></Content>
    <Skus ref="skusRef" @reload-data="getData"></Skus>
  </div>
</template>
